import { useState, useEffect } from 'react';

export interface DeviceInfo {
  isMobile: boolean;
  isTablet: boolean;
  isDesktop: boolean;
  isIOS: boolean;
  isAndroid: boolean;
  hasTouch: boolean;
  browser: string;
  os: string;
}

/**
 * 设备检测工具函数
 * 使用缓存避免重复检测
 */
const detectDevice = (): DeviceInfo => {
  // 从 localStorage 获取缓存
  if (typeof window !== 'undefined') {
    const cached = localStorage.getItem('device-info');
    if (cached) {
      try {
        return JSON.parse(cached);
      } catch {
        // 缓存解析失败，继续检测
      }
    }
  }

  const ua = typeof navigator !== 'undefined' ? navigator.userAgent : '';

  // 操作系统检测
  const isIOS = /iPad|iPhone|iPod/.test(ua) && !(window as any).MSStream;
  const isAndroid = /Android/.test(ua);
  const isWindows = /Windows/.test(ua);
  const isMacOS = /Macintosh|Mac OS X/.test(ua) && !isIOS;

  // 设备类型检测
  const isMobileUA = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(ua);
  const isTabletUA = /iPad|Android(?!.*Mobile)|Tablet/.test(ua);

  // 基于屏幕尺寸的检测
  const width = typeof window !== 'undefined' ? window.innerWidth : 1024;
  const isMobileWidth = width < 768;
  const isTabletWidth = width >= 768 && width < 1024;

  // 综合判断
  const isMobile = isMobileUA || (isMobileWidth && !isTabletUA);
  const isTablet = isTabletUA || (isTabletWidth && !isMobileUA);
  const isDesktop = !isMobile && !isTablet;

  // 触摸支持检测
  const hasTouch = typeof window !== 'undefined' && (
    'ontouchstart' in window ||
    navigator.maxTouchPoints > 0 ||
    (navigator as any).msMaxTouchPoints > 0
  );

  // 浏览器检测
  let browser = 'Unknown';
  if (/Chrome/.test(ua) && !/Edg/.test(ua)) {
    browser = 'Chrome';
  } else if (/Safari/.test(ua) && !/Chrome/.test(ua)) {
    browser = 'Safari';
  } else if (/Firefox/.test(ua)) {
    browser = 'Firefox';
  } else if (/Edg/.test(ua)) {
    browser = 'Edge';
  } else if (/MSIE|Trident/.test(ua)) {
    browser = 'IE';
  }

  // 操作系统名称
  let os = 'Unknown';
  if (isIOS) {
    os = 'iOS';
  } else if (isAndroid) {
    os = 'Android';
  } else if (isWindows) {
    os = 'Windows';
  } else if (isMacOS) {
    os = 'macOS';
  }

  const deviceInfo: DeviceInfo = {
    isMobile,
    isTablet,
    isDesktop,
    isIOS,
    isAndroid,
    hasTouch,
    browser,
    os
  };

  // 缓存结果到 localStorage
  if (typeof window !== 'undefined') {
    try {
      localStorage.setItem('device-info', JSON.stringify(deviceInfo));
    } catch {
      // localStorage 可能被禁用，忽略错误
    }
  }

  return deviceInfo;
};

/**
 * useDeviceDetect Hook
 * 检测设备类型（mobile/tablet/desktop）、操作系统（iOS/Android）和浏览器信息
 *
 * @returns DeviceInfo 对象包含设备和浏览器信息
 *
 * 性能优化：
 * - 检测结果缓存到 localStorage
 * - 仅在首次使用时执行检测
 */
export const useDeviceDetect = (): DeviceInfo => {
  const [deviceInfo] = useState<DeviceInfo>(() => detectDevice());

  useEffect(() => {
    // 监听窗口大小变化，清除缓存（设备类型可能改变）
    const handleResize = () => {
      localStorage.removeItem('device-info');
    };

    // 使用防抖避免频繁清除缓存
    let timeoutId: NodeJS.Timeout;
    const debouncedResize = () => {
      clearTimeout(timeoutId);
      timeoutId = setTimeout(handleResize, 1000);
    };

    window.addEventListener('resize', debouncedResize);
    return () => {
      clearTimeout(timeoutId);
      window.removeEventListener('resize', debouncedResize);
    };
  }, []);

  return deviceInfo;
};
